package com.matt.sooncleaner.notification

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton.OnCheckedChangeListener
import androidx.appcompat.widget.SwitchCompat
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.matt.sooncleaner.R

/**
 *
 * Created by xiexiang10 on 2024/6/17.
 **/
class NotificationAppAdapter : BaseQuickAdapter<AppInfo, QuickViewHolder>() {
    private val mSwitchCheckedChangeListener =
        OnCheckedChangeListener { buttonView, isChecked ->
            val parentView = buttonView.parent as View
            val position = recyclerView.getChildAdapterPosition(parentView)
            val appInfo = getItem(position) ?: return@OnCheckedChangeListener
            if (appInfo.isEnableBlock != isChecked) {
                appInfo.isEnableBlock = isChecked
                NotificationHelper.setEnableBlock(appInfo.packageName, appInfo.isEnableBlock)
            }
        }

    override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: AppInfo?) {
        item ?: return
        holder.setImageDrawable(R.id.appIcon, item.icon)
        holder.setText(R.id.appName, item.appName)
        val switchCompat = holder.getView<SwitchCompat>(R.id.notification_switch)
        switchCompat.setOnCheckedChangeListener(null)
        switchCompat.isChecked = item.isEnableBlock
        switchCompat.setOnCheckedChangeListener(mSwitchCheckedChangeListener)
    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup,
        viewType: Int
    ): QuickViewHolder {
        return QuickViewHolder(R.layout.notification_app_item, parent)
    }
}